from flask import Flask, request, jsonify, render_template
from openai import OpenAI
import os
from utils.file_parser import parse_file
from utils.retry import retry_with_backoff

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024  # 10MB限制

# 初始化Ollama客户端
client = OpenAI(
    base_url='http://localhost:11434/v1',
    api_key='ollama'  # 固定值，实际不验证
)


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/api/chat', methods=['POST'])
@retry_with_backoff(tries=3, delay=1)
def chat():
    data = request.json
    response = client.chat.completions.create(
        model="deepseek-r1:1.5b",
        messages=[{"role": "user", "content": data['prompt']}],
        temperature=0.7,
        max_tokens=2000
    )
    return jsonify({
        'response': response.choices[0].message.content,
        'usage': response.usage.dict()
    })


@app.route('/api/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return jsonify({'error': 'No file uploaded'}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'Empty filename'}), 400

    try:
        text = parse_file(file)
        return jsonify({
            'filename': file.filename,
            'content': text[:5000]  # 限制返回长度
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, threaded=True)
